import { useContext, useState } from "react";
import { FormContext } from './context'


export interface FormInstance<Values = any> {
    __INTERNAL__: {
        name?: string;
    };
    getFieldInstance: (name: any) => any;
};


function useForm(options: any) {
    const { meta } = options
    const valueStore: { [key: string]: any } = {}
    const [error, setError] = useState({});

    function dispatchValue(payload: any) {
        const { name, value } = payload
        if (typeof name === 'string') {
            valueStore[name] = value
        } else if (Array.isArray(name)) {
            let curValue = valueStore
            for (let i = 0; i < name.length; i++) {
                if (i < name.length - 1) {
                    if (!curValue[name[i]]) {
                        curValue[name[i]] = {}
                    }
                    curValue = curValue[name[i]]
                } else {
                    curValue[name[i]] = value
                }
            }
        }
    }

    function getValue(name: string) {
        return valueStore[name] ?? ''
    }

    function getFormValue() {
        return valueStore
    }

    function getFieldType(name: string) {
        const item = getField(name)
        return item?.type ?? 'TEXT'
    }

    function getField(name: string | string[]) {
        if (typeof name === 'string') {
            const item = meta?.children?.find((val: any) => val.name === name)
            return item ?? {}
        } else if (Array.isArray(name)) {
            let curChildren = meta.children
            let i = 0
            let foundNode
            for (; i < name.length; i++) {
                foundNode = curChildren.find(val => val.name === name[i])
                if (!foundNode) {
                    break;
                } else {
                    curChildren = foundNode.children
                }
            }
            if (i === name.length && foundNode) {
                return foundNode
            }
        }
        return {}
    }

    function getRules(fieldName = '') {
        const rules: any[] = [];
        const list = !fieldName ? meta?.children : meta?.children.filter(it => it.name === fieldName);
        list.forEach(it => {
            if(it.required) {
                rules.push({ key: it.name, label: it.label, rules: [{ required: true }] });
            }
        });
        return rules;
    }

    const isEmpty = value => {
        if (value === undefined || value === null || value === '') {
          return true;
        }
        return Array.isArray(value) && value.length === 0;
      };

    const validate = (values, fieldName = '') => {
       return new Promise((resolve, reject) => {
           const formRules = getRules(fieldName);
           const tmpError = {};
           formRules.forEach(rule => {
               const { key, rules, label } = rule;
               const fieldValue = values[key];
               rules.forEach(it => {
                   if(it.required && isEmpty(fieldValue)) {
                    tmpError[key] = `${label}不能为空`
                   }else {
                    tmpError[key] = null;
                   }
               })
           })
           const assignError = {...error, ...tmpError};
           setError(assignError)
           reject(assignError);
       });
    }

    const validateFields = () => {};

    const validateFormFields = async (fieldName = '') => {
        try {
            await validate(valueStore, fieldName);
            return Promise.resolve(valueStore);
        } catch (e) {
            return Promise.reject(e);
        }
    }

    

    return {
        dispatchValue,
        getValue,
        getFormValue,
        getFieldType,
        getField,
        validateFields,
        validateFormFields,
    }
}


export {
    useForm
};